﻿using Dapper;
using Finance.API.Read.Application.Command.PayableManagementCommand;
using Finance.Domain;
using Finance.Dtos;
using Finance.ErrorCode;
using Finance.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace Finance.API.Read.Application.Hander.PayableManagementHander
{
    public class ShowPayableManagementHander:IRequestHandler<ShowPayableManagementCommand,APIPaging<PayableManagementDto>>
    {
        DatabaseContext db;
        ILogger<ShowPayableManagementHander> logger;

        public ShowPayableManagementHander(DatabaseContext db, ILogger<ShowPayableManagementHander> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<APIPaging<PayableManagementDto>> Handle(ShowPayableManagementCommand request, CancellationToken cancellationToken)
        {
            APIPaging <PayableManagementDto> result=new APIPaging<PayableManagementDto> ();
            StringBuilder builder1 = new StringBuilder ();
            StringBuilder sb = new StringBuilder ();
            try
            {
                builder1.Append(@"SELECT PayableManagementId,
		                                a.FlowingWaterNumber,
		                                a.PayableManagementName,
		                                a.PayableManagementType,
		                                a.Recipients,
		                                a.AmountReceivable,
		                                a.PaidInAmount,
		                                a.RemainingAmount,
		                                a.State,
		                                a.LastPaymentDate,
		                                a.Payer,
		                                a.NumberOfPayments,
		                                a.Remark,
                                        a.PaymentInstitutions,
                                        a.CreatTime,
                                        a.CreatName,
                                    b.CategoryName
                                FROM payablemanagement AS a
                                JOIN financialCategory AS b ON a.PayableManagementType=b.FinancialCategoryId
                                WHERE a.IsDel=FALSE");

                sb.Append(@"SELECT
                              COUNT(a.PayableManagementId)
                           FROM payablemanagement AS a
                                JOIN financialCategory AS b ON a.PayableManagementType=b.FinancialCategoryId
                                WHERE a.IsDel=FALSE");


                if (!string.IsNullOrEmpty(request.FlowingWaterNumber))
                {
                    builder1.Append(" AND a.FlowingWaterNumber LIKE @FlowingWaterNumber");
                    sb.Append(" AND a.FlowingWaterNumber LIKE @FlowingWaterNumber");
                }
                if (!string.IsNullOrEmpty(request.PayableManagementName))
                {
                    builder1.Append(" AND a.PayableManagementName LIKE @PayableManagementName");
                    sb.Append(" AND a.PayableManagementName LIKE @PayableManagementName");
                }

                if (request.PayableManagementType.HasValue)
                {
                    builder1.Append(" AND a.PayableManagementType = @PayableManagementType");
                    sb.Append(" AND a.PayableManagementType = @PayableManagementType");
                }

                if (!string.IsNullOrEmpty(request.Recipients))
                {
                    builder1.Append(" AND a.Recipients LIKE @Recipients");
                    sb.Append(" AND a.Recipients LIKE @Recipients");
                }

                if (request.STime != null && request.ETime != null)
                {
                    builder1.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                    sb.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                }

                if (request.State.HasValue)
                {
                    builder1.Append(" AND a.State = @State");
                    sb.Append(" AND a.State = @State");
                }  
                if (request.rid.HasValue)
                {
                    builder1.Append(" AND a.rid = @rid");
                    sb.Append(" AND a.rid = @rid");
                }

                builder1.Append(" ORDER BY a.PayableManagementId DESC LIMIT @PageSize OFFSET @offset");
                var parameters = new
                {
                    FlowingWaterNumber = $"%{request.FlowingWaterNumber}%",
                    PayableManagementName = $"%{request.PayableManagementName}%",
                    request.PayableManagementType,
                    Recipients = $"%{request.Recipients}%",
                    STime = request.STime,
                    ETime = request.ETime,
                    request.State,
                    request.rid,
                    offset = (request.PageIndex - 1) * request.PageSize,
                    request.PageSize
                };

                var pageData = await db.DapperConnection.QueryAsync<PayableManagementDto>(builder1.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(sb.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                result.PageDatas = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPage = totalPage;
                result.Message = "应付管理显示成功";
                result.Code = APIEnum.Ok;
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("应付管理显示失败" + ex.Message);
                throw;
            }
        }
    }
}
